import styles from './index.module.scss'
import Icon from '@/components/Icon'
import { useAppSelector } from '@/store'
import {
  addChannel,
  changeChannelId,
  deleteChannel,
  getAllChannels,
  getUserChannels,
} from '@/store/action/channel'
import { Popup, Tabs } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import lodash from 'lodash'
import classNames from 'classnames'
import { Channel as ChannelType } from '@/store/reducer/channel'
import history from '@/utils/history'

export default function Channel() {
  // 发送请求获取频道列表
  const dispatch = useDispatch()
  useEffect(() => {
    // 获取用户频道
    dispatch(getUserChannels())
    // 获取所有频道
    dispatch(getAllChannels())
  }, [dispatch])

  // 获取 redux 中频道列表数据
  const { list, allList } = useAppSelector((state) => state.channel)

  // allList  所有频道
  // list     我的频道
  // leftList 计算剩下频道 = 所有频道 - 我的频道
  // const leftList = allList.filter((item) => {
  //   // 查找我的频道是否出现过
  //   const obj = list.find((v) => v.id === item.id)
  //   // console.log('filter里', obj)
  //   // 出现过就返回 false，表示过滤掉
  //   return obj ? false : true
  // })
  // 利用 lodash 根据 id 计算剩余的频道
  const leftList = lodash.differenceBy(allList, list, 'id')

  // console.log('filter外allList', allList)
  // console.log('filter外list', list)
  // console.log('filter外leftList', leftList)

  // 频道编辑弹出层开关变量
  const [popupShow, setPopupShow] = useState(false)

  // 当前选中的频道 id，默认值是推荐频道 id 为 0
  // const [activeId, setActiveId] = useState(0)
  const { activeId } = useAppSelector((state) => state.channel)

  // 频道是否可编辑
  const [editable, setEditable] = useState(false)

  const handleAdd = (item: ChannelType) => {
    // console.log(item)
    dispatch(addChannel(item))
  }

  return (
    <div>
      {/* 顶部频道 tabs */}
      <div className={styles.channelTabs}>
        <Tabs
          className='tabs'
          activeKey={String(activeId)}
          onChange={(key: string) => dispatch(changeChannelId(Number(key)))}
        >
          {/* 💥踩坑：Tabs.TabPane 在 v5.0.0-beta.22 版本改名称为 Tabs.Tab */}
          {/* https://github.com/ant-design/ant-design-mobile/issues/4409 */}
          {/* 以前写法：<Tabs.TabPane title='水果' key='fruits' /> */}
          {/* 新版写法：<Tabs.Tab title='水果' key='fruits' /> */}
          {list.map((item) => (
            <Tabs.Tab title={item.name} key={item.id} />
          ))}
        </Tabs>
        <div className='right'>
          <Icon type='iconbtn_search' onClick={() => history.push('/search')} />
          <Icon type='iconbtn_channel' onClick={() => setPopupShow(true)} />
        </div>
      </div>
      {/* 编辑频道弹出层 */}
      <Popup visible={popupShow} position='left' bodyClassName={styles.channelPopup}>
        {/* 顶部栏：带关闭按钮 */}
        <div className='channel-header'>
          <Icon type='iconbtn_channel_close' onClick={() => setPopupShow(false)} />
        </div>

        {/* 频道列表 */}
        <div className='channel-content'>
          {/* 当前已选择的频道列表 */}
          <div className={classNames('channel-item', editable ? 'edit' : '')}>
            <div className='channel-item-header'>
              <span className='channel-item-title'>我的频道</span>
              <span className='channel-item-title-extra'>点击进入频道</span>
              <span className='channel-item-edit' onClick={() => setEditable(!editable)}>
                {editable ? '完成' : '编辑'}
              </span>
            </div>

            <div className='channel-list'>
              {/* 用户频道列表 list */}
              {list.map((item) => (
                <span
                  key={item.id}
                  className={classNames('channel-list-item', item.id === activeId ? 'actived' : '')}
                  onClick={(e) => {
                    // 设置频道 id 高亮效果
                    dispatch(changeChannelId(item.id))
                    // 关闭弹出层
                    setPopupShow(false)
                  }}
                >
                  {item.name}
                  <Icon
                    onClick={(e: React.MouseEvent<HTMLOrSVGElement, MouseEvent>) => {
                      e.stopPropagation()
                      dispatch(deleteChannel(item.id))
                    }}
                    type='iconbtn_tag_close'
                  />
                </span>
              ))}
            </div>
          </div>

          {/* 推荐的频道列表 */}
          <div className='channel-item'>
            <div className='channel-item-header'>
              <span className='channel-item-title'>频道推荐</span>
              <span className='channel-item-title-extra'>点击添加频道</span>
            </div>
            <div className='channel-list'>
              {/* 剩下的频道 leftList */}
              {leftList.map((item) => (
                <span onClick={() => handleAdd(item)} key={item.id} className='channel-list-item'>
                  + {item.name}
                </span>
              ))}
            </div>
          </div>
        </div>
      </Popup>
    </div>
  )
}
